﻿using System;
using System.Collections.Generic;
using System.Text;
using CAUNetLogin.Entity;
using CAUNetLogin.Util.SystemLib;
using CAUNetLogin.NetUtil.ReturnMessage;
using System.IO;
using CAUNetLogin.Util.Entity;
using System.Windows.Forms;
using CAUNetLogin.Util.Validate;

namespace CAUNetLogin.Util
{
    public class UIUpdate
    {
        public Account user;
        public NetState netState;
        public SucceedMessage succeedMsg;
        public FailedMessage failedMsg;

        /// <summary>
        /// 初始化数据
        /// </summary>
        public UIUpdate()
        {
            netState = new NetState();
            user = new Account();
            succeedMsg = new SucceedMessage();
            failedMsg = new FailedMessage();
            netState.GetNetState();
            if (File.Exists(ConfigManager.configFilePath))
            {
                ConfigManager.GetAccount(ref user);
                ConfigManager.savePassword = true;
            }

            if (ConfigManager.CheckAutoStart(ConfigManager.autoRunKeyName))
            {
                ConfigManager.startWithWindows = true;
            }
            if (Registery.CUCheckRegistery(@"Software\CAUNetLogin", "ExitAfterConnect", "1"))
            {
                ConfigManager.exitAfterConnect= true;
            }
            if (Registery.CUCheckRegistery(@"Software\CAUNetLogin", "AutoConnect", "1"))
            {
                ConfigManager.autoConnect = true;
            }
        }


        public string  Connect(Account account,ref bool isSucceed,bool isFailedMessage)
        {
            isSucceed = false;
            isFailedMessage = false;
            if (DataValidate.IsEmpty(account.User))
            {
                return "账户不能为空";
            }
            if (DataValidate.IsEmpty(account.Password))
            {
                return "密码不能为空";
            }
            if (ConfigManager.savePassword)
            {
                user = account;
                ConfigManager.SaveAccount(user);
            }
            if (ConfigManager.savePassword == false && File.Exists(ConfigManager.configFilePath))
            {
                File.Delete(ConfigManager.configFilePath);
            }
            if (netState.Ping("61.135.169.105", "123.129.194.177"))
            {
                return  "网络已经连接,不要重复连接!";
            }

            NetConnect netConnect = new NetConnect();
            string result = "";
            if (netConnect.ConnectSucceed(user, ref result))
            {
                isSucceed = true;
                succeedMsg.ParseMsg(result);
                return "网络已成功连接!";
            }
            else
            {
                failedMsg.ParseMsg(result);
                return "网络连接失败!";
            }
        }

    }
}
